package com.dgz.test.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/07/22/09:02
 * @Description:
 */
//基于内存的会话记忆
@RestController
@RequestMapping("chat-memory")
public class ChatMemoryController {

    private ChatClient client;

    public ChatMemoryController(ChatModel chatModel) {
        this.client = ChatClient.builder(chatModel)
                .defaultSystem("你是一个旅游规划师，请根据用户的需求提供旅游规划建议")
                .defaultAdvisors(
//                        MessageChatMemoryAdvisor 消息对话记忆拦截器
                        new MessageChatMemoryAdvisor(
//                                基于内存方式的对话记忆
                                new InMemoryChatMemory()
                        )
                )
                .build();
    }


    @RequestMapping("memory")
    public Flux<String> memory(@RequestParam("prompt") String prompt,
                               @RequestParam("chatId") String chatId,
                               HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        return client.prompt(prompt).advisors(
                a -> a
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY,100)
        ).stream().content();
    }
}
